from flask import Blueprint, request, jsonify
from .calculator import FemaleFitnessCalculator

female_bp = Blueprint('female', __name__, url_prefix='/api/female')


@female_bp.route('/calculate', methods=['POST'])
def calculate_female_score():
    """计算女生体能考核分数"""
    try:
        data = request.get_json()

        # 验证必需字段
        required_fields = ['age', 'height', 'weight', 'run3000', 'snakeRun', 'pullUp', 'sitUp']
        for field in required_fields:
            if field not in data:
                return jsonify({
                    'error': f'缺少必需字段: {field}'
                }), 400

        # 解析输入数据
        age = int(data['age'])
        height = float(data['height'])
        weight = float(data['weight'])
        run3000 = data['run3000']
        snakeRun = data['snakeRun']
        pullUp = int(data['pullUp'])
        sitUp = int(data['sitUp'])

        # 计算BMI
        bmi = FemaleFitnessCalculator.calculate_bmi(height, weight)
        bmi_grade = FemaleFitnessCalculator.calculate_bmi_grade(age, bmi)

        # 解析3000米时间
        run3000_seconds = FemaleFitnessCalculator.parse_time(run3000)
        if run3000_seconds is None:
            return jsonify({
                'error': '3000米时间格式错误，请使用 MM:SS 格式'
            }), 400

        # 计算各项得分
        scores = {
            'run3000': FemaleFitnessCalculator.get_score('3000米', age, run3000_seconds),
            'snakeRun': FemaleFitnessCalculator.get_score('蛇形跑', age, float(snakeRun)),
            'pullUp': FemaleFitnessCalculator.get_score('引体向上', age, pullUp),
            'sitUp': FemaleFitnessCalculator.get_score('仰卧卷腹', age, sitUp)
        }

        # 计算总分
        total_score = sum(scores.values())

        # 获取各项等级
        grades = {
            'run3000': FemaleFitnessCalculator.get_grade('3000米', scores['run3000']),
            'snakeRun': FemaleFitnessCalculator.get_grade('蛇形跑', scores['snakeRun']),
            'pullUp': FemaleFitnessCalculator.get_grade('引体向上', scores['pullUp']),
            'sitUp': FemaleFitnessCalculator.get_grade('仰卧卷腹', scores['sitUp'])
        }

        # 获取总等级
        total_grade = FemaleFitnessCalculator.get_total_grade(total_score, scores)

        # 返回结果
        result = {
            'gender': 'female',
            'bmi': bmi,
            'bmiGrade': bmi_grade,
            'scores': scores,
            'grades': grades,
            'total': total_score,
            'totalGrade': total_grade,
            'details': {
                'age': age,
                'height': height,
                'weight': weight,
                'run3000': run3000,
                'snakeRun': snakeRun,
                'pullUp': pullUp,
                'sitUp': sitUp
            }
        }

        return jsonify(result)

    except ValueError as e:
        return jsonify({
            'error': '数据格式错误，请检查输入数据'
        }), 400
    except Exception as e:
        return jsonify({
            'error': f'计算过程中发生错误: {str(e)}'
        }), 500


@female_bp.route('/health', methods=['GET'])
def female_health():
    """女生API健康检查"""
    return jsonify({
        'status': 'healthy',
        'message': '女生体能考核API服务运行正常',
        'gender': 'female'
    })


@female_bp.route('/projects', methods=['GET'])
def get_female_projects():
    """获取女生考核项目信息"""
    projects_info = {}
    for project_name, project_data in FemaleFitnessCalculator.SCORE_TABLES.items():
        projects_info[project_name] = {
            'type': project_data['type'],
            'age_groups': list(project_data['data'].keys())
        }

    return jsonify({
        'gender': 'female',
        'projects': projects_info
    })